<template>
  <div>
    <a-space v-if="!isEdit" :size="10">
      <span>{{ showValue }}</span>
      <span><icon-edit class="cell-icon" @click="editCell()"/></span>
    </a-space>
    <a-space v-else :size="10">
      <span v-if="type === 'text'">
        <a-input v-model="formValue" placeholder=""/>
      </span>
      <span v-else-if="type === 'textarea'">
        <a-textarea v-model="formValue" placeholder="" :auto-size="{maxRows:3}" allow-clear/>
      </span>
      <span v-else-if="type === 'date'">
        <a-date-picker v-model="formValue" show-time format="YYYY-MM-DD HH:mm:ss"/>
      </span>
      <span><icon-check class="cell-icon" @click="okCBK()"/></span>
      <span><icon-close class="cell-icon" @click="cancel()"/></span>
    </a-space>
  </div>
</template>

<script setup>
  // 编辑单元格
  import { ref, computed, onMounted } from 'vue';
  import { Message } from '@arco-design/web-vue';

  const props = defineProps({
    // 字段
    field: {
      type: String,
      required: true,
    },
    // 字段值
    value: {
      type: [Number, String],
      required: true,
    },
    // 数据
    data: {
      type: Object,
      required: true,
    },
    // 类型
    type: {
      type: String,
      default: 'text',
    },
    // 选项
    options: {
      type: Array,
      default() {
        return [];
      },
    },
    required: {
      type: Boolean,
      default: false,
    },
  });

  const emit = defineEmits(['editTableCallback']);

  const showValue = computed({
    get() {
      return props.value;
    },
    set(val) {

    },
  });
  const isEdit = ref(false);
  const formValue = ref();

  // 编辑
  const editCell = () => {
    isEdit.value = true;
  };
  // 确认
  const okCBK = () => {
    const formData = props.data;
    if (!formValue.value && props.required) {
      Message.info('不能为空');
    } else {
      formData[props.field] = formValue.value;
      emit('editTableCallback', formData);
      showValue.value = formValue.value;
      isEdit.value = false;
    }
  };
  // 取消
  const cancel = () => {
    formValue.value = props.value;
    isEdit.value = false;
  };

  onMounted(() => {
    formValue.value = props.value;
  });
</script>

<style lang="less">
  .cell-icon {
    cursor: pointer;
  }
</style>
